package org.durandj.ystream.server.network.packetHandlers;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.durandj.ystream.server.Server;
import org.durandj.ystream.server.network.Client;
import org.durandj.ystream.server.network.Packet;
import org.durandj.ystream.server.network.PacketHandler;

/**
 * Handles the Ping packet. The handler will log the time difference between when the packet was sent and
 * when it was received.
 * 
 * @author durandj
 * @version 1.0
 *
 */
public class PingPacketHandler extends PacketHandler
{
	/**
	 * Creates a packet handler for the ping opcode.
	 */
	public PingPacketHandler()
	{
		super();
	}
	
	/* (non-Javadoc)
	 * @see org.durandj.ystream.client.network.PacketHandler#handlePacket(org.durandj.ystream.client.network.Packet)
	 */
	@Override
	protected void handlePacket(Packet packet)
	{
		// First let's get the time that the packet was sent.
		long time = packet.getContents().getLong();
		
		time = System.currentTimeMillis() - time;
		
		// Now we need the client that sent return ping.
		try
		{
			Client client = Server.getServer().getClientManager().getClient(InetAddress.getByName(packet.getSource()));
			
			// Set the client's latency.
			client.setLatency(time);
			
			log.info("Latency for client " + packet.getSource() + " is " + client.getLatency() + " milliseconds.");
		}
		catch(UnknownHostException e)
		{
			// This shouldn't be reached unless the client got disconnected.
		}
	}
}
